#-*-coding:utf8;-*-
from matplotlib.pyplot import savefig
from numpy import flatiter, left_shift, nan
from numpy.lib.function_base import append
import pandas as pd
import time
import numpy as np
import mplfinance as mpf
import os
import tushare as ts
# from  chinese_calendar  import is_holiday
import datetime
from ylTDX import * #from ylTDX import all def function

pd.options.mode.chained_assignment = None #avoid :pandas SettingWithCopyWarning
ts.set_token("6667cd4a2326f2f937062a0f4fb59aea5c56d13b1f6f26225f115fe9")

def zjjr(file_name,code):                      
    days=60
    Today=time.strftime("%Y-%m-%d-%H-%M-%S")
    YEAR=int(Today.split('-')[0])
    MONTH=int(Today.split('-')[1])
    pro = ts.pro_api()
    end_date_str=time.strftime("%Y%m%d")
    end_datetime = datetime.datetime.strptime(end_date_str, '%Y%m%d') 
    start_datetime=n_days_before(end_datetime,days)
    start_date_str=start_datetime.strftime("%Y%m%d")
    try:
        df = pro.daily(ts_code='{}.SZ'.format(str(code).zfill(6)), start_date=start_date_str, end_date=end_date_str)       
    except Exception as e:
        print(e)
        time.sleep(60) 
        df = pro.daily(ts_code='{}.SZ'.format(str(code).zfill(6)), start_date=start_date_str, end_date=end_date_str)
    df.set_index('trade_date',inplace=True)
    df.sort_index(inplace=True)   
    df.rename(columns={'vol': 'volume'},inplace=True)  
    df_new=df[["open","high","low","close","volume","amount"]]
    OPEN=df_new["open"].to_list() #open 是file open
    HIGH=df_new["high"].to_list()
    LOW=df_new["low"].to_list()
    CLOSE=df_new["close"].to_list()  
    VOLUME=df_new["volume"].to_list() 
    AMOUNT=df_new["amount"].to_list() 
    VARC=LOW
    VARD=REF(LOW,1)
    # VARE:=SMA(ABS(VARC-VARD),3,1)/SMA(MAX(VARC-VARD,0),3,1)*100;
    VARE=multiply(divide(SMA(ABS(subtraction(VARC,VARD)),3,1),SMA(MAX(subtraction(VARC,VARD),0),3,1)),100)
    # VARF:=MA(VARE/10,3);
    VARF=MA(divide(VARE,10),3)
    # VAR10:=LLV(LOW,30);
    VAR10=LLV(LOW,30)
    #VAR11:=HHV(VARF,30);
    VAR11=HHV(VARF,30)
    # 主力观望:MA(IF(LOW<=VAR10,(VARF+VAR11*2)/2,0),3);
    主力观望= MA([VARF[i]/2+VAR11[i] if LOW[i]<=VAR10[i] else 0 for i in range(len(LOW))],3)
    # VAR1B:=REF((LOW+OPEN+CLOSE+HIGH)/4,1);
    VAR1B=REF(divide(ADDS(LOW,OPEN,CLOSE,HIGH),4),1)
    # VAR2B:=SMA(ABS(LOW-VAR1B),13,1)/SMA(MAX(LOW-VAR1B,0),10,1);
    VAR2B=divide(SMA(ABS(subtraction(LOW,VAR1B)),13,1),SMA(MAX(subtraction(LOW,VAR1B),0),10,1))
    # VAR3B:=EMA(VAR2B,10);
    VAR3B=EMA(VAR2B,10)
    # VAR4B:=LLV(LOW,33);
    VAR4B=LLV(LOW,33)
    # VAR5B:=EMA(IF(LOW<=VAR4B,VAR3B,0),3)*3;
    VAR5B=multiply(EMA([VAR3B[i] if LOW[i]<=VAR4B[i] else 0 for i in range(len(LOW))],3),3)
    # 资金介入:IF(VAR5B>REF(VAR5B,1),VAR5B,0),COLORRED,LINETHICK6;
    主力进场=[VAR5B[i] if VAR5B[i]>REF(VAR5B,1)[i] else 0 for i in range(len(VAR5B))]
    # STICKLINE(VAR5B>REF(VAR5B,1),0,VAR5B,3,0 ),COLORRED;
    # 洗盘:IF(VAR5B<REF(VAR5B,1),VAR5B,0),COLORGREEN;
    洗盘=[VAR5B[i] if VAR5B[i]<REF(VAR5B,1)[i] else 0 for i in range(len(VAR5B))]
    # VAR1:=REF((LOW+OPEN+CLOSE+HIGH)/4,1);
    VAR1=REF(divide(ADDS(LOW,OPEN,CLOSE,HIGH),4),1)
    # VAR2:=SMA(ABS(LOW-VAR1),13,1)/SMA(MAX(LOW-VAR1,0),10,1);
    VAR2=divide(SMA(ABS(subtraction(LOW,VAR1)),13,1),SMA(MAX(subtraction(LOW,VAR1),0),10,1))
    # VAR3:=EMA(VAR2,10);
    VAR3=EMA(VAR2,10)
    # VAR4:=LLV(LOW,33);
    VAR4=LLV(LOW,33)
    # VAR5:=EMA(IF(LOW<=VAR4,VAR3,0),3);
    VAR5=EMA([VAR3[i] if LOW[i]<=VAR4[i] else 0 for i in range(len(LOW))],3)
    # STICKLINE(VAR5>REF(VAR5,1),0,VAR5,6,0 ),COLORGREEN;
    stick_green=[0 if VAR5[i]>REF(VAR5,1)[i] else VAR5[i] for i in range(len(VAR5))]
    # STICKLINE(VAR5<REF(VAR5,1),0,VAR5,6,0),COLORRED;
    stick_red=[0 if VAR5[i]<REF(VAR5,1)[i] else VAR5[i] for i in range(len(VAR5))]
    # 铁峰参数:VAR5>REF(VAR5,4) {AND C>REF(C,1)},COLORFFFF00; #{}注释符号
    铁峰参数=[1 if VAR5[i]>REF(VAR5,4)[i] else 0 for i in range(len(VAR5))]
    # VAR2C:=(HIGH+LOW+CLOSE*2)/4;
    VAR2C=divide(ADDS(LOW,HIGH,multiply(CLOSE,2)),4)
    # VAR3C:=EMA(VAR2C,7);
    VAR3C=EMA(VAR2C,7)
    # VAR4C:=STD(VAR2C,7);
    VAR4C=STD(VAR2C,7)
    # VAR5C:=(VAR2C-VAR3C)*100/VAR4;
    VAR5C=divide(multiply(subtraction(VAR2C,VAR3C),100),VAR4)
    # VAR6C:=EMA(VAR5C,3);
    VAR6C=EMA(VAR5C,3)
    # WW:(EMA(VAR6C,5)+100)/2-3,COLORFF00FF;
    WW=subtraction(divide(ADD(EMA(VAR6C,5),100),2),3)
    # print(ww)
    # MM:HHV(WW,3),COLORFF3333;
    MM=HHV(WW,3)
    AAA=divide(divide(AMOUNT,VOLUME),100)

    output_File = open(file_name,'a+') 
    output_File.write('{},{},{}\n'.format(str(code).zfill(6),str(round(主力进场[-1],2)),df_new['close'][-1]))
    output_File.flush()
    return "%s complete"%str(code).zfill(6)


def multi_thread_zljc_check(file_name,code_list):
    """
    使用线程池，由系统自动分配线程数量，并打印线程目标函数的返回结果
    """  
    #在append之前先删除原数据表
    import concurrent.futures
    with concurrent.futures.ThreadPoolExecutor() as executor:     
        results=[ executor.submit(zjjr,file_name,i) for i in code_list]
        for f in concurrent.futures.as_completed(results):
            print(f.result())      

if __name__=='__main__':
    path=os.getcwd()
    # df=pd.read_csv(path+'/after_process.csv')
    # df1=df[["code",'f10']]
    # df1.query('f10==True',inplace=True)
    # df1.drop(columns=['f10'],inplace=True)
    # df1.to_csv("f10_true.csv")
    df1=pd.read_csv(path+'/f10_true.csv')
    code_index_list=df1['code'].to_list()
    # file_name="{}.csv".format("zhu_li_jin_chang_"+str(time.strftime("%Y_%m_%d_%H")))
    file_name="zljc.csv" #主力进场
    if os.path.exists(file_name): os.remove(file_name)
    output_File = open(file_name,'a+')
    output_File.write('{},{},{}\n'.format('code','zljc','close'))
    output_File.flush()
    multi_thread_zljc_check(file_name,code_index_list)  
    #zljc由大到小排序
    df_res=pd.read_csv(file_name,encoding='unicode_escape') 
    df_res.columns=['code','zljc','close']
    df_res.sort_values(by='zljc',ascending=False,inplace=True)
    df_res.to_csv(file_name)